package pkg

import (
	"errors"
	"github.com/xuri/excelize/v2"
	"strconv"
)

func ReadTitles(path string) (res []string, err error) {
	file, err := excelize.OpenFile(path)
	if err != nil {
		return
	}
	defer file.Close()
	index := file.GetActiveSheetIndex()
	list := file.GetSheetList()
	if len(list) == 0 {
		return res, errors.New("没有可用的工作表")
	}
	rows, err := file.GetRows(list[index])
	if err != nil {
		return
	}
	if len(rows) == 0 {
		return res, errors.New("工作表中没有数据")
	}
	return rows[0], nil
}

// ReadAndSaveFile 读取分割保存文件
func ReadAndSaveFile(readPath, savePath string, index int, prefix string) error {
	f, err := excelize.OpenFile(readPath)
	if err != nil {
		return errors.New("读取excel文件失败")
	}
	defer f.Close()

	sheetIndex := f.GetActiveSheetIndex()
	list := f.GetSheetList()
	if len(list) == 0 {
		return errors.New("被拆分的excel文件内容为空")
	}
	rows, err := f.GetRows(list[sheetIndex])
	if err != nil {
		return errors.New("读取excel内容失败，请检查文件是否被占用")
	}
	rowLen := len(rows)
	if rowLen <= 1 {
		return errors.New("被拆分的excel文件内容为空")
	}

	// 标题
	titleRow := rows[0]
	sheetMap := make(map[string]int)

	file := excelize.NewFile()

	for i := 1; i < rowLen; i++ {
		// 判断分sheet值
		tmpSheet := prefix + rows[i][index]
		if tmpSheet == "" {
			tmpSheet = "空"
		}
		if _, ok := sheetMap[tmpSheet]; !ok {
			sheetMap[tmpSheet] = 1
			// 创建新的sheet
			file.NewSheet(tmpSheet)
			// 添加表头
			err := file.SetSheetRow(tmpSheet, "A1", &titleRow)
			if err != nil {
				return errors.New("添加表头出错")
			}
		}
		// 如果sheet存在直接添加数据
		nextLine := sheetMap[tmpSheet] + 1
		nextLineKey := "A" + strconv.Itoa(nextLine)
		file.SetSheetRow(tmpSheet, nextLineKey, &rows[i])
		// 序号加1
		sheetMap[tmpSheet] = nextLine
	}
	// 删除默认的Sheet1
	file.DeleteSheet("Sheet1")
	err = file.SaveAs(savePath)
	return err
}
